"""
背景图类
"""
import cv2 as cv
from Official import Text, Img, TextEngine
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import textwrap
import os



class Background:
    """
        背景图（模板类）
    """

    def __init__(self, path):
        """
        初始方法
        :param path: 模板路径
        """
        self.path = path
        self.win_name = ''
        self.shrink = 0

        self.background: Image.Image = Image.open(self.path)
        self.width = self.background.width
        self.height = self.background.height

        self.begin_height = 0
        self.shrink_background: Image.Image = self.background.copy()

    def show(self, win_name: str, shrink: int):
        """
        显示背景图
        :param win_name: 窗口名称
        :param shrink: 缩放倍数
        """
        self.shrink = shrink
        self.shrink_background = self.background.resize((int(self.width / self.shrink), int(self.height / self.shrink)))
        background = cv.cvtColor(np.asarray(self.shrink_background), cv.COLOR_RGB2BGR)
        cv.imshow(win_name, background)
        cv.waitKey()
        cv.destroyAllWindows()

    def insert_title(self, title: Text):
        """
        设置标题，要求：加粗，居中，可以设置换行，并且可以自动换行
        :param title: 标题
        """
        # 计算标题宽度
        line_width = self.width - (title.margin * 2)
        # 切割固定步长的文本
        font_length = line_width // title.font_size
        lines = textwrap.wrap(title.text, width=font_length)
        # 组装填充开始位置
        height = title.top

        draw = ImageDraw.Draw(self.background)
        font_style = ImageFont.truetype("C:\WINDOWS\Fonts\微软雅黑\msyhbd.ttc", title.font_size, encoding="utf-8")
        # 绘制文本
        for line in lines:
            # 绘制每一行文本
            # 让文字居中
            font_width = title.font_size * len(line)
            width = (line_width - font_width) // 2 + title.margin
            draw.text((width, height), line, title.font_color, font_style)
            height += title.font_size + 10
            self.begin_height = height

    def insert_subheading(self, subheading: Text):
        """
        插入副标题，需求定格显示，需要换行
        :param subheading: 副标题
        """
        line_width = self.width - (subheading.margin * 2)
        # 切割固定步长的文本
        length = line_width // subheading.font_size
        lines = textwrap.wrap(subheading.text, width=length)
        draw = ImageDraw.Draw(self.background)
        font_style = ImageFont.truetype("C:\WINDOWS\Fonts\微软雅黑\msyhbd.ttc", subheading.font_size, encoding="utf-8")
        height = self.begin_height + subheading.top
        width = subheading.margin
        for line in lines:
            draw.text((width, height), line, subheading.font_color, font_style)
            height += subheading.font_size + 10
            width = subheading.margin
            self.begin_height = height


    def insert_substance(self, substance: Text):
        """
        插入内容 目标：首行缩进两个字符，自动换行，实现边距
        :param substance: 要插入的副标题
        """
        line_width = self.width - (substance.margin * 2)
        engine = TextEngine(substance.text, line_width, substance.font_size)
        # 切割固定步长的文本
        draw = ImageDraw.Draw(self.background)
        font_style = ImageFont.truetype("C:\WINDOWS\Fonts\微软雅黑\msyh.ttc", substance.font_size, encoding="utf-8")
        y = self.begin_height + substance.top
        font_size = substance.font_size
        x = substance.margin + (substance.font_size * 2)
        is_last = False
        for line_index in range(len(engine.all_line)):
            line = engine.all_line[line_index]
            for index in range(len(line)):
                # extra_margin = engine.calculate_punctuation(line_index, index)
                font = line[index]
                # x = x + extra_margin
                if is_last is True:
                    # 最后一个字减去间隔
                    is_last = False
                    # x = x - (extra_margin * 2)
                    # x =
                draw.text((x, y), font, substance.font_color, font_style)
                # 判断是不是标点符号
                if engine.is_punctuation(font) is True:
                    # 是标点符号,占半个字符
                    x = x + (font_size // 2)
                else:
                    # x = x + font_size + extra_margin
                    x = x + font_size

                if x + font_size > line_width:
                    is_last = True
                if x > line_width:
                    x = substance.margin
                    y = y + font_size + 10
        self.begin_height = y + font_size + 10

    def insert_img(self, img: Img):
        """
        插入图片,需求：将图片插入到模板中,多大进行缩放，适合等比缩放就等比缩放，裁剪则居中裁剪
        :param img: 图片
        """
        img_width = self.width - (img.margin * 2)
        img_height = self.height - self.begin_height - (img.top * 2)

        img.center_cropping(img_width, img_height)

        # 求缩放比例
        position = (img.margin, self.begin_height + img.top)
        self.background.paste(img.original_img, position)

    def save(self, path: str, file_name: str):
        """
        保存图片到本地 jpg
        :param path: 要保存的文件夹
        :param file_name: 要保存的文件名
        """
        path_list = path.split('/')
        url = ""
        for path_url in path_list:
            url = os.path.join(url, path_url)
            if not os.path.exists(url):
                os.makedirs(url)
        file = os.path.join(url, file_name)
        self.background.save(file)

    def reset_template(self):
        """
        重置图片模板
        """
        self.win_name = ''
        self.shrink = 0

        self.background: Image.Image = Image.open(self.path)
        self.width = self.background.width
        self.height = self.background.height

        self.begin_height = 0
        self.shrink_background: Image.Image = self.background.copy()




